package flink.examples;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author : wuxinquan
 * @date: 2024/5/30 - 05 - 30 - 10:24
 * @Description: flink.examples
 * @version: 1.0
 */
public class SocketStreamWordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream<String> source = env.socketTextStream("192.168.111.128", 7000);
        DataStream<Tuple2<String, Integer>> singleWordDataStream = source.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {
                Arrays.stream(line.split(" ")).forEach(singleWord -> out.collect(Tuple2.of(singleWord, 1)));
            }
        }).returns(Types.TUPLE(Types.STRING,Types.LONG));
        DataStream<Tuple2<String, Integer>> wordCountDataStream = singleWordDataStream.keyBy(v -> v.f0).sum(1);
        DataStreamSink<Tuple2<String, Integer>> print = wordCountDataStream.print();
        env.execute();
    }
}
